package jannex.sql.extensions;

import jannex.Jannex;
import jannex.internal.ExceptionFactory;
import jannex.internal.ReflectionUtils;
import jannex.sql.TypedArray;
import jannex.sql.TypedResultSet;

import java.sql.Array;
import java.sql.SQLException;
import java.util.Map;

public class TypedArrayImpl<E> extends ArrayImpl implements TypedArray<E> {

    private final Class<E> elementClass;

    public TypedArrayImpl(Array array, Jannex jannex, Class<E> elementClass) {
        super(array, jannex);
        this.elementClass = elementClass;
    }

    @Override
    public E[] getArray() {
        try {
            return ReflectionUtils.castArray(elementClass, array.getArray());
        } catch (SQLException e) {
            throw ExceptionFactory.make(e);
        }
    }

    @Override
    public E[] getArray(Map<String, Class<?>> map) {
        try {
            return ReflectionUtils.castArray(elementClass, array.getArray(map));
        } catch (SQLException e) {
            throw ExceptionFactory.make(e);
        }
    }

    @Override
    public E[] getArray(long index, int count) {
        try {
            return ReflectionUtils.castArray(elementClass, array.getArray(index, count));
        } catch (SQLException e) {
            throw ExceptionFactory.make(e);
        }
    }

    @Override
    public E[] getArray(long index, int count, Map<String, Class<?>> map) {
        try {
            return ReflectionUtils.castArray(elementClass, array.getArray(index, count, map));
        } catch (SQLException e) {
            throw ExceptionFactory.make(e);
        }
    }

    @Override
    public TypedResultSet<E> getResultSet(long index, int count, Map<String, Class<?>> map) {
        return new TypedResultSetImpl<>(super.getResultSet(index, count, map), jannex, jannex.getHandler(elementClass));
    }

    @Override
    public TypedResultSet<E> getResultSet() {
        return new TypedResultSetImpl<>(super.getResultSet(), jannex, jannex.getHandler(elementClass));
    }

    @Override
    public TypedResultSet<E> getResultSet(Map<String, Class<?>> map) {
        return new TypedResultSetImpl<>(super.getResultSet(map), jannex, jannex.getHandler(elementClass));
    }

    @Override
    public TypedResultSet<E> getResultSet(long index, int count) {
        return new TypedResultSetImpl<>(super.getResultSet(index, count), jannex, jannex.getHandler(elementClass));
    }

}
